package com.hhc.bookmarkmanager.service;

import com.hhc.bookmarkmanager.dto.BookmarkDTO;
import com.hhc.bookmarkmanager.exception.ResourceNotFoundException;
import com.hhc.bookmarkmanager.model.Bookmark;
import com.hhc.bookmarkmanager.repository.BookmarkRepository;
import lombok.RequiredArgsConstructor;

import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class BookmarkService {

    private final BookmarkRepository bookmarkRepository;
    private final ModelMapper modelMapper;




    public List<BookmarkDTO> getAllBookmarks() {
        return bookmarkRepository.findAll()
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public List<BookmarkDTO> searchBookmarks(String query) {
        return bookmarkRepository.search(query)
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public BookmarkDTO getBookmarkById(Long id) {
        Bookmark bookmark = bookmarkRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Bookmark not found with id: " + id));
        return convertToDTO(bookmark);
    }

    public BookmarkDTO createBookmark(BookmarkDTO bookmarkDTO) {
        Bookmark bookmark = convertToEntity(bookmarkDTO);
        Bookmark savedBookmark = bookmarkRepository.save(bookmark);
        return convertToDTO(savedBookmark);
    }

    public BookmarkDTO updateBookmark(Long id, BookmarkDTO bookmarkDTO) {
        Bookmark existingBookmark = bookmarkRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Bookmark not found with id: " + id));

        existingBookmark.setTitle(bookmarkDTO.getTitle());
        existingBookmark.setUrl(bookmarkDTO.getUrl());
        existingBookmark.setImageUrl(bookmarkDTO.getImageUrl());

        Bookmark updatedBookmark = bookmarkRepository.save(existingBookmark);
        return convertToDTO(updatedBookmark);
    }

    public void deleteBookmark(Long id) {
        if (!bookmarkRepository.existsById(id)) {
            throw new ResourceNotFoundException("Bookmark not found with id: " + id);
        }
        bookmarkRepository.deleteById(id);
    }

    private BookmarkDTO convertToDTO(Bookmark bookmark) {
        return modelMapper.map(bookmark, BookmarkDTO.class);
    }

    private Bookmark convertToEntity(BookmarkDTO bookmarkDTO) {
        return modelMapper.map(bookmarkDTO, Bookmark.class);
    }
}
